﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace BASIC_ES_API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class HomeController : ControllerBase
    {

        [HttpPost("GetMenu")]
        public IActionResult GetMenu()
        {
            //var builder = new ConfigurationBuilder();
            //builder.AddJsonFile("Config/WebComOAMenu.json");
            //var configuration = builder.Build();

            //将Json转换回列表
            var directorypath = Directory.GetCurrentDirectory();
            string strFileName = directorypath + "\\Config\\WebComOAMenu.json";
            string jsonData = GetJsonFile(strFileName);
            // Console.WriteLine(jsonData);
            //反序列化Json字符串内容为对象
            var jsondata = JsonConvert.DeserializeObject<List<MenuView>>(jsonData);

            return Ok(jsondata);
        }

        /// <summary>
        /// InsertUserMenu
        /// </summary>
        /// <returns></returns>
        [HttpPost("InsertUserMenu")]
        public IActionResult InsertUserMenu(string userId, List<string> menuCodes)
        {
            var directorypath = Directory.GetCurrentDirectory();
            string strFileName = directorypath + "\\Config\\WebComOAMenu.json";
            string jsonData = GetJsonFile(strFileName);

            //处理老菜单
            var meuns = GetMenuList();
            var userMenus = JsonConvert.DeserializeObject<List<MenuView>>(jsonData);
            var deleteMenus = userMenus.Where(p => p.UserId == userId).ToList();
            deleteMenus.ForEach(p => userMenus.Remove(p));

            //添加新菜单
            foreach (var item in menuCodes)
            {
                var meun = meuns.Where(p => p.Code == item);
                if (meun.Count() > 0)
                {
                    var model = meun.FirstOrDefault();
                    userMenus.Add(new MenuView()
                    {
                        Code = model.Code,
                        PCode = model.PCode,
                        Name = model.Name,
                        Level = model.Level,
                        Sort = model.Sort,
                        UserId = userId
                    });
                }
            }

            //把模型数据写到文件  
            using (StreamWriter sw = new StreamWriter(strFileName, false, Encoding.GetEncoding("GB2312")))
            {
                try
                {
                    JsonSerializer serializer = new JsonSerializer();
                    serializer.Converters.Add(new JavaScriptDateTimeConverter());
                    serializer.NullValueHandling = NullValueHandling.Ignore;


                    //构建Json.net的写入流  
                    JsonWriter writer = new JsonTextWriter(sw);
                    //把模型数据序列化并写入Json.net的JsonWriter流中  
                    serializer.Serialize(writer, userMenus);
                    //ser.Serialize(writer, ht);  
                    writer.Close();
                    sw.Close();

                }
                catch (Exception)
                {

                }
            }

            return Ok("ok");
        }

        /// <summary>
        /// DeleteUserMenu
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpPost("DeleteUserMenu")]
        public IActionResult DeleteUserMenu(string userId)
        {
            var directorypath = Directory.GetCurrentDirectory();
            string strFileName = directorypath + "\\Config\\WebComOAMenu.json";
            string jsonData = GetJsonFile(strFileName);

            //处理老菜单
            var meuns = GetMenuList();
            var userMenus = JsonConvert.DeserializeObject<List<MenuView>>(jsonData);
            var deleteMenus = userMenus.Where(p => p.UserId == userId).ToList();
            deleteMenus.ForEach(p => userMenus.Remove(p));

            //把模型数据写到文件  
            using (StreamWriter sw = new StreamWriter(strFileName, false, Encoding.GetEncoding("GB2312")))
            {
                try
                {
                    JsonSerializer serializer = new JsonSerializer();
                    serializer.Converters.Add(new JavaScriptDateTimeConverter());
                    serializer.NullValueHandling = NullValueHandling.Ignore;


                    //构建Json.net的写入流  
                    JsonWriter writer = new JsonTextWriter(sw);
                    //把模型数据序列化并写入Json.net的JsonWriter流中  
                    serializer.Serialize(writer, userMenus);
                    //ser.Serialize(writer, ht);  
                    writer.Close();
                    sw.Close();

                }
                catch (Exception)
                {

                }
            }

            return Ok("ok");
        }

        /// <summary>
        /// DeleteUserMenu
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpPost("test")]
        public IActionResult test(int month)
        {
            string cooperateTime = string.Empty;
            if (month <= 1)
            {
                cooperateTime = "合作时间 1个月";
            }
            else if (month < 12)
            {
                cooperateTime = $"合作时间 {month}个月";
            }
            else if (month >= 12)
            {
                var year = month / 12;
                if ((year * 12) == month)
                    cooperateTime = $"合作时间 {year}年";
                else
                    cooperateTime = $"合作时间 {year}年{(month % 12)}个月";
            }

            return Ok(cooperateTime);
        }

        public static string GetJsonFile(string filepath)
        {
            string json = string.Empty;
            using (FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                using (StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("GB2312")))
                {
                    json = sr.ReadToEnd().ToString();
                }
            }
            return json;
        }


        /// <summary>
        /// 判读按服务器环境
        ///       Linux服务器路径与windows不同
        /// </summary>
        /// <returns></returns>
        private string GetJsonFileName()
        {
            var directorypath = Directory.GetCurrentDirectory();
            string strFileName = "";
            if (IsLinuxRunTime())
                strFileName = directorypath + "/Config/WebComOAMenu.json";
            else
                strFileName = directorypath + "\\Config\\WebComOAMenu.json";

            return strFileName;
        }

        private static bool IsLinuxRunTime()
        {
            return RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
        }


        [HttpPost("TestMenu")]
        public List<MenuView> TestMenu()
        {
            List<MenuView> menus = new List<MenuView>();
            menus.Add(new MenuView()
            {
                PCode = "",
                Code = "workorder",
                Name = "工单",
                Level = 1,
                Sort = 1,
                UserId = "QueDaoQiu",
            });

            menus.Add(new MenuView()
            {
                PCode = "",
                Code = "qyorder",
                Name = "签约",
                Level = 1,
                Sort = 2,
                UserId = "QueDaoQiu",
            });

            menus.Add(new MenuView()
            {
                PCode = "qyorder",
                Code = "qyorder_qy",
                Name = "签约",
                Level = 2,
                Sort = 1,
                UserId = "QueDaoQiu",
            });
            menus.Add(new MenuView()
            {
                PCode = "qyorder",
                Code = "qyorder_xy",
                Name = "签约",
                Level = 2,
                Sort = 2,
                UserId = "QueDaoQiu",
            });

            menus.Add(new MenuView()
            {
                PCode = "",
                Code = "payorder",
                Name = "支付单",
                Level = 1,
                Sort = 3,
                UserId = "QueDaoQiu",
            });

            menus.Add(new MenuView()
            {
                PCode = "payorder",
                Code = "payorder_qy",
                Name = "签约",
                Level = 2,
                Sort = 1,
                UserId = "QueDaoQiu",
            });

            menus.Add(new MenuView()
            {
                PCode = "payorder",
                Code = "payorder_xy",
                Name = "续约",
                Level = 2,
                Sort = 2,
                UserId = "QueDaoQiu",
            });

            menus.Add(new MenuView()
            {
                PCode = "payorder",
                Code = "payorder_recharge",
                Name = "充值",
                Level = 2,
                Sort = 3,
                UserId = "QueDaoQiu",
            });

            return menus;
        }

        private List<MenuView> GetMenuList()
        {
            List<MenuView> menus = new List<MenuView>();
            menus.Add(new MenuView()
            {
                PCode = "",
                Code = "workorder",
                Name = "工单",
                Level = 1,
                Sort = 1,
                UserId = "QueDaoQiu",
            });

            menus.Add(new MenuView()
            {
                PCode = "",
                Code = "qyorder",
                Name = "签约",
                Level = 1,
                Sort = 2,
                UserId = "QueDaoQiu",
            });

            menus.Add(new MenuView()
            {
                PCode = "qyorder",
                Code = "qyorder_qy",
                Name = "签约",
                Level = 2,
                Sort = 1,
                UserId = "QueDaoQiu",
            });
            menus.Add(new MenuView()
            {
                PCode = "qyorder",
                Code = "qyorder_xy",
                Name = "签约",
                Level = 2,
                Sort = 2,
                UserId = "QueDaoQiu",
            });

            menus.Add(new MenuView()
            {
                PCode = "",
                Code = "payorder",
                Name = "支付单",
                Level = 1,
                Sort = 3,
                UserId = "QueDaoQiu",
            });

            menus.Add(new MenuView()
            {
                PCode = "payorder",
                Code = "payorder_qy",
                Name = "签约",
                Level = 2,
                Sort = 1,
                UserId = "QueDaoQiu",
            });

            menus.Add(new MenuView()
            {
                PCode = "payorder",
                Code = "payorder_xy",
                Name = "续约",
                Level = 2,
                Sort = 2,
                UserId = "QueDaoQiu",
            });

            menus.Add(new MenuView()
            {
                PCode = "payorder",
                Code = "payorder_recharge",
                Name = "充值",
                Level = 2,
                Sort = 3,
                UserId = "QueDaoQiu",
            });

            return menus;
        }
    }



    public class UserRole
    {
        public string UserId { get; set; }
        public string Nmae { get; set; }
    }

    public class MenuView
    {
        public string Code { get; set; }
        public string PCode { get; set; }
        public string Name { get; set; }
        public int Level { get; set; }
        public int Sort { get; set; }
        public string UserId { get; set; }
    }

    public class Menu
    {
        public string Code { get; set; }
        public string Name { get; set; }
        public int Level { get; set; }
        public int Sort { get; set; }
    }
}
